package com.gis.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gis.bean.Api;
import com.gis.util.Constant;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;

/**
 * judge whether request is login, and whether request is authorized
 * @author Administrator
 *
 */
public class LoginFilter implements Filter {
	private String excludedPages;
    private String[] excludedPageArray;
	@Override
	public void init(FilterConfig config) throws ServletException {
		// 读取web.xml中配置的排除路径
		excludedPages = config.getInitParameter("excludedPages");
		if (StrUtil.isNotEmpty(excludedPages)) {
			this.excludedPageArray = excludedPages.split(",");
        }
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)servletrequest;
		HttpServletResponse httpServletResponse =  (HttpServletResponse)servletresponse;
		
		// 获取请求的资源路径
		String requestURI = httpServletRequest.getRequestURI();
		requestURI = StrUtil.subAfter(requestURI, "/webgis", true);
		boolean isExclude = false;
		for (String excludedPage : excludedPageArray) {
			if (requestURI.startsWith("/static") || excludedPage.equals(requestURI)) {
				isExclude = true;
				break;
			}
		}
		
		// 如果请求的资源被排除
		if (isExclude) {
			filterchain.doFilter(servletrequest, servletresponse);
			return;
		}
		
		// 从request中获取SessionId
		HttpSession session = httpServletRequest.getSession();
		String username = (String) session.getAttribute("username");
		if (username == null) {
			Log.get().error(Constant.USER_NOT_LOGIN);
			ResponseUtil.writeJson(httpServletResponse, RestResponse.fail(Constant.USER_NOT_LOGIN));
			return;
		}
		// 获取session 中保存的用户权限列表
		List<Api> permissions = (List<Api>) session.getAttribute("permissions");
		if(permissions == null) {
			ResponseUtil.writeJson(httpServletResponse, RestResponse.fail(Constant.USER_NOT_LOGIN));
			return;
		}
		
		boolean b = false;
		// 判断所请求的资源是否存在于权限列表中
		for (Api permission : permissions) {
			if (permission.getApiUrl().equals(requestURI)) {
				b = true;
				break;
			}
		}
		if(b) {
			filterchain.doFilter(servletrequest, servletresponse);
		} else {
			Log.get().info("用户{}未授权，资源{}", username, requestURI);
			ResponseUtil.writeJson(httpServletResponse, RestResponse.fail(Constant.NOT_AUTHORIZED));
			return;
		}
	}

}
